package com.pd.kit;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;

/**
 * Created by dong peng
 * DATE : 2016/12/20
 * TIME : 22:51.
 */


public class UrlConnectionKit {

    public static String getRequest(String reqUrl, String dataStr){
        return httpRequest(reqUrl,"GET",dataStr);
    }

    public static String postRequest(String reqUrl, String dataStr){
       return httpRequest(reqUrl,"POST",dataStr);
    }

    /**
     * 通过java类库自带的URLConnection类实现http请求
     *
     * @param reqUrl
     * @param reqMethod
     * @param dataStr
     * @return
     */
    private static String httpRequest(String reqUrl,String reqMethod, String dataStr){
        String result = null;
        InputStream in = null;
        OutputStream out = null;
        HttpsURLConnection httpsConn = null;

        try{
            URL url = new URL(reqUrl);
            httpsConn = (HttpsURLConnection) url.openConnection();

            // 设置链接类的属性
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            httpsConn.setConnectTimeout(10000);
            httpsConn.setReadTimeout(10000);
            httpsConn.setRequestMethod(reqMethod);

            // 建立连接
            httpsConn.connect();

            // 写数据到请求
            if(dataStr != null) {
                out = new BufferedOutputStream(httpsConn.getOutputStream());
                out.write(dataStr.getBytes("UTF-8"));
            }

            // 处理请求返回的数据
            in = httpsConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String lineStr = null;
            StringBuffer sbf = new StringBuffer();
            while ((lineStr = bufferedReader.readLine()) != null) {
                sbf.append(lineStr);
            }

            result = sbf.toString();

        }catch (Exception e) {
            System.out.println("发送请求出现异常! " + e);
            e.printStackTrace();
        }finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in != null) {
                    in.close();
                }
                if(httpsConn != null) {
                    httpsConn.disconnect();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }
}
